package com.fenxiao.mytask.dao.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.type.StandardBasicTypes;

import com.fenxiao.base.BaseDaoImpl;
import com.fenxiao.common.Pager;
import com.fenxiao.mytask.dao.UserTaskDao;
import com.fenxiao.mytask.entity.UserTask;
import com.fenxiao.task.entity.TaskScreenshot;
import com.fenxiao.user.entity.User;
import com.fenxiao.util.OrderNumber;

public class UserTaskDaoImpl extends BaseDaoImpl<UserTask> implements
		UserTaskDao {

	private SessionFactory sessionFactory;

	@Override
	public int addUserTask(UserTask userTask) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().save(userTask);
		return 1;
	}

	@Override
	public UserTask queryUserTask(long taskId, long userId) {
		// TODO Auto-generated method stub
		String hql = "select u from UserTask u where u.taskId=" + taskId
				+ " and u.user.id=" + userId + " and u.taskStatus=5 or u.taskId=" + taskId
				+ " and u.user.id=" + userId + " and u.taskStatus=2";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		Object obj = query.uniqueResult();
		// Object obj=query.uniqueResult();
		if (obj != null) {
			return (UserTask) obj;
		} else {
			return null;
		}
	}

	@Override
	public List<UserTask> queryPeopleTask(long userId) {
		// TODO Auto-generated method stub
		String hql = "select u from UserTask u where u.user.id=" + userId
				+ " ORDER BY u.taskOrderTime DESC";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List<UserTask> list = query.list();
		if (list != null) {
			return list;
		} else {
			return null;
		}
	}

	@Override
	public UserTask queryUserTaskById(long userTaskId) {
		// TODO Auto-generated method stub
		String hql = "select u from UserTask u where u.userTaskId="
				+ userTaskId;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		Object obj = query.uniqueResult();
		if (obj != null) {
			return (UserTask) obj;
		} else {
			return null;
		}
	}

	@Override
	public int updateAppRegisterName(long userTaskId, String appRegisterName) {
		// TODO Auto-generated method stub appRegisterName
		String hql = "update UserTask u set u.appRegisterName='"
				+ appRegisterName + "'  where u.userTaskId=" + userTaskId;
		return sessionFactory.getCurrentSession().createQuery(hql)
				.executeUpdate();
	}

	@Override
	public List<UserTask> queryThoseTaskCompleted(long userId) {
		// TODO Auto-generated method stub
		String hql = "select u from UserTask u where u.taskStatus=2 and u.user.id="
				+ userId + "ORDER BY taskCompletionTime DESC";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List<UserTask> list = query.list();
		if (list != null) {
			return list;
		} else {
			return null;
		}
	}

	@Override
	public int updateWeChatReply(String content,
			String weChatOfficialAccountReply, String originalID) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());

		String hql = "update UserTask u set u.weChatOfficialAccountReply='"
				+ weChatOfficialAccountReply
				+ "',u.taskStatus=2,u.taskCompletionTime='" + date
				+ "' where u.originalID='" + originalID
				+ "' and u.taskType=1 and u.randomCode='" + content + "'";
		return sessionFactory.getCurrentSession().createQuery(hql)
				.executeUpdate();
	}
//团队奖金
	@Override
	public List queryTeamTaskForTheMan(User user) {
		// TODO Auto-generated method stub
		String hql = "SELECT t FROM UserTask t join t.user us WHERE t.user.id IN (SELECT id FROM User u WHERE u.recomCode='"
				+ user.getRecommendationCode()
				+ "') AND t.taskStatus=2 "
				+ "ORDER BY taskCompletionTime DESC";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List list = query.list();

		if (list != null) {
			return list;
		} else {
			return null;
		}
	}

	@Override
	public UserTask queryUserTaskByReply(String content, String originalID) {
		// TODO Auto-generated method stub
		String hql = "select u from UserTask u left join u.user where u.randomCode='"
				+ content + "' and u.originalID='" + originalID + "'";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		Object obj = query.uniqueResult();
		if (obj != null) {
			return (UserTask) obj;
		} else {
			return null;
		}
	}

	@Override
	public List<UserTask> shaixuan(long userId, Integer taskStatus,
			Integer taskType, Integer taskPrice) throws ParseException {
		// TODO Auto-generated method stub
		String hql = "select u from UserTask u where u.user.id=" + userId;
		String hql1 = " and u.taskStatus=" + taskStatus;
		String hql2 = " and u.taskType=" + taskType;
		String hql3 = null;
		if (taskStatus != null) {
			hql += hql1;
		}
		if (taskType != null) {
			hql += hql2;
		}
		if (taskPrice != null) {
			/*
			 * SimpleDateFormat dft = new
			 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date beginDate = new
			 * Date(); Calendar date = Calendar.getInstance();
			 * date.setTime(beginDate); date.set(Calendar.DATE,
			 * date.get(Calendar.DATE) + taskTime); Date endDate =
			 * dft.parse(dft.format(date.getTime()));
			 * System.out.println(endDate); String str=dft.format(endDate);
			 */
			if (taskPrice == 1) {
				hql3 = "order by u.taskBonus desc";
			} else if (taskPrice == 2) {
				hql3 = "order by u.taskBonus asc";
			} else {
				hql3 = "order by taskOrderTime desc";
			}

			hql += hql3;
		}
		System.out.println(hql);
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List list = query.list();
		if (list != null) {
			return list;
		} else {
			return null;
		}

	}

	/**
	 * 查询所有的APP审核任务
	 */
	public Pager queryAppTaskPage(int pageSize, int page, String search) {
		String hql = "from UserTask t left join t.user u  where t.taskType<>1 and t.taskStatus=5";
		if (search != null && !"".equals(search.trim())) {
			hql += "and t.taskTitle like'%" + search + "%'";
		}
		hql += " order by t.taskOrderTime desc";
		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);

		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;

	}

	/**
	 * 查询所有记录数
	 * 
	 * @param hql
	 *            查询的条件
	 * @return 总记录数
	 */
	public int getAllRowCount(String hql) {
		Session session = sessionFactory.openSession();
		List list = null;
		try {
			Query query = session.createQuery(hql);

			list = query.list();

		} catch (RuntimeException e) {
			throw e;
		}
		session.close();
		return list.size();

	}

	/**
	 * 分页查询
	 * 
	 * @param hql
	 *            查询的条件
	 * @param offset
	 *            开始记录
	 * @param length
	 *            一次查询几条记录
	 * @return
	 */
	public List queryForPage(String hql, int offset, int length) {
		Session session = sessionFactory.openSession();
		List list = null;
		try {
			Query query = session.createQuery(hql);
			query.setFirstResult(offset);
			query.setMaxResults(length);
			list = query.list();

		} catch (RuntimeException e) {
			throw e;
		}
		session.close();
		return list;
	}

	/**
	 * 查询任务截图
	 */
	public List<TaskScreenshot> queryShotList(UserTask userTask) {
		String hql = "from TaskScreenshot ts where ts.userTask.userTaskId="
				+ userTask.getUserTaskId();
		Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
		List<TaskScreenshot> list = query.list();
		if (list != null) {
			return list;
		} else {
			return null;
		}
	}

	/**
	 * 详情
	 */
	public UserTask queryUserTaskInfo(long userTaskId) {
		String hql = "from UserTask ut where ut.userTaskId=" + userTaskId;
		Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
		Object obj = query.uniqueResult();
		if (obj != null) {
			return (UserTask) obj;
		} else {
			return null;
		}

	}

	/**
	 * 获取订单编号
	 */
	public String getOrderCode() {

		String recomCode = OrderNumber.orderCodePrefix
				+ OrderNumber.getFormatDate();
		String hql = "select max(userTaskId) from UserTask";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		Object obj = query.uniqueResult();
		if (obj == null) {
			long obj0 = 1;
			String obj1 = String.format("%08d", obj0);
			recomCode = recomCode + obj1;
			return recomCode;
		} else {
			String obj2 = String.format("%08d", obj);
			String codes = obj2.substring(obj2.length() - 8, obj2.length());
			int codei = Integer.parseInt(codes) + 1;
			return recomCode + String.format("%08d", codei);
		}

	}

	/**
	 * 修改
	 */
	public int updateUserTask(UserTask userTask) {
		this.sessionFactory.getCurrentSession().update(userTask);
		return 1;
	}

	/**
	 * 查询所有的已审核任务
	 */
	public Pager queryAllTaskPage(int pageSize, int page, String search) {
		String hql = "from UserTask t left join t.user u  where t.taskType<>1 and t.taskStatus<>5";
		if (search != null && !"".equals(search.trim())) {
			hql += "and t.taskTitle like'%" + search + "%'";
		}
		hql += " order by t.taskCompletionTime desc";
		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);

		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;
	}
	/**
	 * 查询所有成功的已审核任务
	 */
	public Pager queryAllTaskPageChengong(int pageSize, int page, String search,int zhuangtia,String modile,long hehuoId,long dailiId,long yuanId) {
		String hql = "from UserTask t left join t.user u  where  t.taskStatus=2";
		if (search != null && !"".equals(search.trim())) {
			hql += " and t.taskTitle like'%" + search + "%'";
		}
		if(zhuangtia!=0){
			hql+=" and t.taskType="+zhuangtia;
		}
		if(modile!=null&&!"".equals(modile)){
			hql+=" and u.mobile="+modile;
		}
		if(hehuoId!=0&&hehuoId!=-1){
			hql+=" and u.partnerId="+hehuoId;
		}
		if(dailiId!=0&&dailiId!=-1){
			hql+=" and u.agentsId="+dailiId;
		}
		if(yuanId!=0&&yuanId!=-1){
			hql+=" and u.sadffId="+yuanId;
		}
		hql += " order by t.taskCompletionTime desc";
		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);
		
		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;
	}
	/**
	 * 查询所有成功的已审核任务
	 */
	public Double queryAllTaskshouyi( String search,int zhuangtia,String modile,long hehuoId,long dailiId,long yuanId) {
		String hql = "select SUM(t.taskBonus1) from UserTask t left join t.user u  where  t.taskStatus=2";
		if (search != null && !"".equals(search.trim())) {
			hql += "and t.taskTitle like'%" + search + "%'";
		}
		if(zhuangtia!=0){
			hql+=" and t.taskType="+zhuangtia;
		}
		if(modile!=null&&!"".equals(modile)){
			hql+=" and u.mobile="+modile;
		}
		if(hehuoId!=0&&hehuoId!=-1){
			hql+=" and u.partnerId="+hehuoId;
		}
		if(dailiId!=0&&dailiId!=-1){
			hql+=" and u.agentsId="+dailiId;
		}
		if(yuanId!=0&&yuanId!=-1){
			hql+=" and u.sadffId="+yuanId;
		}
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		Object obj = query.uniqueResult();
		if (obj != null) {
			return  (Double) obj;
		} else {
			return null;
		}
	}

	/**
	 * 批量删除
	 */
	public int deleteUserTask(String numbers) {
		String hql = "delete from UserTask ut where ut.userTaskId in ("
				+ numbers + ")";
		String hql1 = "delete from TaskScreenshot ts where ts.userTask.userTaskId in ("
				+ numbers + ")";
		this.sessionFactory.getCurrentSession().createQuery(hql1)
				.executeUpdate();
		this.sessionFactory.getCurrentSession().createQuery(hql)
				.executeUpdate();
		return 1;

	}

	/**
	 * 删除
	 */
	public int deleteTask(long userTaskId) {

		String hql = "delete from UserTask ut where ut.userTaskId="
				+ userTaskId;
		String hql1 = "delete from TaskScreenshot ts where ts.userTask.userTaskId="
				+ userTaskId;
		this.sessionFactory.getCurrentSession().createQuery(hql1)
				.executeUpdate();
		this.sessionFactory.getCurrentSession().createQuery(hql)
				.executeUpdate();
		return 1;
	}

	@Override
	public int updateUserTaskUploadTime(UserTask userTask) {
		// TODO Auto-generated method stub
		String hql = "update UserTask u set u.uploadTime="
				+ userTask.getUploadTime() + 1 + " where u.userTaskId="
				+ userTask.getUserTaskId();
		return sessionFactory.getCurrentSession().createQuery(hql)
				.executeUpdate();
	}

	@Override
	public int updateUserTaskByMessage(String content, String reply) {
		// TODO Auto-generated method stub taskStatus
		String hql = "update UserTask u set u.weChatOfficialAccountReply='"
				+ reply + "',u.taskStatus=2 where u.randomCode='" + content
				+ "'";
		return sessionFactory.getCurrentSession().createQuery(hql)
				.executeUpdate();
	}

	public List queryGuanZhuUser(long taskId) {
		String hql = "from UserTask us left join us.user where us.taskStatus=2 and us.taskId="
				+ taskId;
		Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
		List list = query.list();
		if (list != null) {
			return list;
		} else {
			return null;
		}
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	// 完成任务查询
	@Override
	public List<UserTask> queryUserTasks(long taskId, long userId) {
		// TODO Auto-generated method stub
		String hql = "select u from UserTask u where u.taskId=" + taskId
				+ " and u.user.id=" + userId;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List obj = query.list();
		// Object obj=query.uniqueResult();
		if (obj != null) {
			return obj;
		} else {
			return null;
		}
	}
//我的任务查询
	@Override
	public Pager queryMyTask(int pageSize, int page,long userId) {
		String hql = "select u from UserTask u where u.user.id=" + userId + " ORDER BY u.taskOrderTime DESC" ;

		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);

		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;
	}

	@Override
	public Pager queryMyTaskfy(int pageSize, int page, long userId,
			Integer taskStatus, Integer taskType, Integer taskPrice) {
		String hql = "select u from UserTask u where u.user.id=" + userId;
		String hql1 = " and u.taskStatus=" + taskStatus;
		String hql2 = " and u.taskType=" + taskType;
		String hql3 = null;
		if (taskStatus != null&&taskStatus != 0) {
			hql += hql1;
		}
		if (taskType != null&&taskType != 0) {
			hql += hql2;
		}
		if (taskPrice != 0) {
			/*
			 * SimpleDateFormat dft = new
			 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date beginDate = new
			 * Date(); Calendar date = Calendar.getInstance();
			 * date.setTime(beginDate); date.set(Calendar.DATE,
			 * date.get(Calendar.DATE) + taskTime); Date endDate =
			 * dft.parse(dft.format(date.getTime()));
			 * System.out.println(endDate); String str=dft.format(endDate);
			 */
			if (taskPrice == 1) {
				hql3 = "order by u.taskBonus desc";
			} else if (taskPrice == 2) {
				hql3 = "order by u.taskBonus asc";
			} else {
				hql3 = "order by taskOrderTime desc";
			}

			hql += hql3;
		}
		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);

		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;
	}
	//分页查询推广佣金
	public Pager queryTaskPagetuiguan(int pageSize,int page,User user){
		String hql = "SELECT t FROM UserTask t  left join fetch t.user us WHERE t.user.id IN (SELECT id FROM User u WHERE u.recomCode='"
				+ user.getRecommendationCode()
				+ "') AND t.taskStatus=2"
				+ "ORDER BY taskCompletionTime DESC";
		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);

		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;
	}
	//分页查询推广佣金
	public Pager queryTaskMyyj(int pageSize,int page,long userId){
		String hql = "select u from UserTask u where u.taskStatus=2 and u.user.id="
				+ userId + "ORDER BY taskCompletionTime DESC";
		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);
		
		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;
	}

	@Override
	public Pager queryTaskPagetuangdui(int pageSize, int page, User user) {
		String hql = "SELECT t FROM UserTask t left join fetch t.user us WHERE t.user.id IN (SELECT id FROM User u WHERE u.recomCode='"
				+ user.getRecommendationCode()
				+ "') AND t.taskStatus=2 "
				+ "ORDER BY taskCompletionTime DESC";
		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);

		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;
	}

	@Override
	public Pager queryMyTaskZt(int pageSize, int page, long userId,
			Integer taskStatus, Integer taskType, Integer taskPrice) {
		String hql = "select u from UserTask u where u.user.id=" + userId;
		String hql1 = " and u.taskStatus=" + taskStatus;
		String hql2 = " and u.taskType=" + taskType;
		String hql3 = null;
		if (taskStatus != null) {
			hql += hql1;
		}
		if (taskType != null) {
			hql += hql2;
		}
		if (taskPrice != null) {
			/*
			 * SimpleDateFormat dft = new
			 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date beginDate = new
			 * Date(); Calendar date = Calendar.getInstance();
			 * date.setTime(beginDate); date.set(Calendar.DATE,
			 * date.get(Calendar.DATE) + taskTime); Date endDate =
			 * dft.parse(dft.format(date.getTime()));
			 * System.out.println(endDate); String str=dft.format(endDate);
			 */
			if (taskPrice == 1) {
				hql3 = "order by u.taskBonus desc";
			} else if (taskPrice == 2) {
				hql3 = "order by u.taskBonus asc";
			} else {
				hql3 = "order by taskOrderTime desc";
			}

			hql += hql3;
		}
		int allRow = this.getAllRowCount(hql);
		int totalPage = Pager.countTotalPage(pageSize, allRow);
		final int offset = Pager.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = Pager.countCurrentPage(page);
		List list = this.queryForPage(hql, offset, length);

		Pager pages = new Pager();
		pages.setPageSize(pageSize);
		pages.setCurrentPage(currentPage);
		pages.setAllRow(allRow);
		pages.setTotalPage(totalPage);
		pages.setList(list);
		pages.init();
		return pages;
	}

	@Override
	public List<UserTask> queryAllTaskdaisheng() {
		String hql = "from UserTask u where u.taskStatus=1" ;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List obj = query.list();
		// Object obj=query.uniqueResult();
		if (obj != null) {
			return obj;
		} else {
			return null;
		}
	}

}
